//
//  HJSettingViewController.m
//  Sneakers
//
//  Created by 胡光健 on 2017/11/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJSettingViewController.h"
#import "HJEditUserNameViewController.h"
#import "HJResetPasswordController.h"
#import "HJAboutUsViewController.h"

@interface HJSettingViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headImage;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *tellPhone;

@property (weak, nonatomic) IBOutlet UILabel *cache;
@property (weak, nonatomic) IBOutlet UILabel *versions;


@property(nonatomic,strong)NSString * imageStr;

@property(nonatomic,strong)UIButton * btn;
@end

@implementation HJSettingViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Fill 1"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
   [self configBtmView];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self removeFromBtn];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    [mNotificationCenter addObserver:self selector:@selector(editmemberNotification:) name:@"editmemberNotification" object:nil];
    self.tableView.separatorColor = HJColorAlpha(0, 0, 0, 0.1);
    self.headImage.layer.cornerRadius = 24;
    self.headImage.layer.masksToBounds = YES;
    
    
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[self.userModel avatar_base_url],[self.userModel avatar_path]]] placeholderImage:HJImage(@"atovor1")];
    self.name.text = [self.userModel nickname];
    self.tellPhone.text = [self.userModel mobile];
    self.cache.text = [NSString stringWithFormat:@"%.2fMB",[CommonTools readCacheSize]];
    self.versions.text = [NSString stringWithFormat:@"V%@版本",[CommonTools appVersion]];
    
}

- (void)back:(UIBarButtonItem *)item {
    [self removeFromBtn];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row==0) {
        [TZImagePickerTool selectImageForEditFrom:self complete:^(UIImage *origionImg, UIImage *editedImage) {
            self.headImage.image = editedImage;
            [self updataHeadImg:editedImage isIcon:YES];
        }];
    }else if (indexPath.row==1) {
        [self removeFromBtn];
        WeakSelf
        UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HJEditUserNameViewController * editUserVC = [sb instantiateViewControllerWithIdentifier:@"editUserName"];
        editUserVC.editUserNameBlock = ^(NSString *username) {
            weakSelf.name.text = username;
        };
        [self.navigationController pushViewController:editUserVC animated:YES];
    }else if (indexPath.row==3) {
        [self removeFromBtn];
        UIStoryboard * sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HJResetPasswordController * resetVC = [sb instantiateViewControllerWithIdentifier:@"ResetPassword"];
        resetVC.mobile = self.userModel.mobile;
        [self.navigationController pushViewController:resetVC animated:YES];
    }else if (indexPath.row==4) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否清理缓存" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 1000;
        [alert show];
    }else if (indexPath.row==5) {
        [self removeFromBtn];
        HJAboutUsViewController * vc = [[HJAboutUsViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }

}
- (void)updataHeadImg:(UIImage *)image isIcon:(BOOL)isIcon {
    if (!image) return;
    [self showTextHUDWithPleaseWait];
    [TZHttpTool uploadImageWithUrl:SolaImageApi params:nil image:image completion:^(NSDictionary *result, NSError *error) {
        self.imageStr = result[@"path"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"editmemberNotification" object:nil userInfo:@{@"img":result[@"path"]}];
        });
        [self hideTextHud];
    }];
}
-(void)editmemberNotification:(NSNotification *)not {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"avatar_path"] = not.userInfo[@"img"];
    params[@"nickname"] = not.userInfo[@"nickname"];
    [TZHttpTool post:UpdateMemberAPI params:params success:^(NSDictionary *result) {
        [self showHint:@"修改成功"];
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (alertView.tag==100) {
        if (buttonIndex==1) {
            [self removeFromBtn];
            // 注销成功 下次启动时不自动登录
            [mUserDefaults setObject:@"0" forKey:@"isLogin"];
            [mUserDefaults setObject:@"" forKey:@"authToken"];
            [mUserDefaults synchronize];
            [HJEaseManager loginOut];
            [mNotificationCenter postNotificationName:@"outLoginNotification" object:nil];
//            [mNotificationCenter postNotificationName:@"outLogin" object:nil];
            self.tabBarController.selectedIndex = 0;
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else {
        if (buttonIndex==1) {
            [CommonTools clearFile];
            self.cache.text = @"0.00MB";
        }
    }
}

-(void)configBtmView {
    CGFloat H;
    if (mScreenHeight<812) {
        H = mScreenHeight -60;
    }else {
        H = mScreenHeight-60-X_Bottom_Space;
    }
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.frame = CGRectMake(0, H, mScreenWidth, 60);
    self.btn.tag = 222;
    [self.btn setTitle:@"退出登录" forState:UIControlStateNormal];
    [self.btn setTitleColor:HJColorRGB(0) forState:UIControlStateNormal];
    self.btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    [self.btn setBackgroundColor:HJColorRGB(255)];
    self.btn.layer.shadowOpacity = 0.2;
    self.btn.layer.shadowRadius = 3;
    self.btn.layer.shadowOffset = CGSizeZero;
    self.btn.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.btn addTarget:self action:@selector(outLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.tabBarController.view addSubview:self.btn];
   
}

-(void)outLogin {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否退出登录" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 100;
    [alert show];
}

-(void)removeFromBtn {
    UIButton * btn = [self.tabBarController.view  viewWithTag:222];
    [btn removeFromSuperview];
}
@end
